package com.yaodian100.mall.member.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;

import com.yaodian100.core.admin.entity.MemberDetails;
import com.yaodian100.mall.member.util.UserData;

/**
 * 
 * @author afra.chou
 * 
 */
public class UserFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		try {
			UserData userData = new UserData(httpRequest, httpResponse);
			MemberDetails memberDetail = new MemberDetails(userData.getMemberId());
			memberDetail.setLoginId(userData.getLoginId());
			boolean isLogin = isLogin(userData);
			if (isLogin) {
				SecurityContextHolder.getContext().setAuthentication(
						new UsernamePasswordAuthenticationToken(memberDetail, "password"));

			}
			chain.doFilter(request, response);
			SecurityContextHolder.getContext().setAuthentication(null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SecurityContextHolder.getContext().setAuthentication(null);
		}

	}

	public void init(FilterConfig arg0) throws ServletException {

	}

	private boolean isLogin(UserData userData) throws Exception {
		if (StringUtils.isNotBlank(userData.getLoginId())) {
			return true;
		}
		return false;
	}
}